<script setup lang="ts">
import { ref } from "vue"
import { ElMessage } from 'element-plus'
import { Trash2 } from '@vben/icons'
import ImagePreviewActions from './image-preview-actions.vue'
import { $t } from '@vben/locales';

defineOptions({ name: 'OptionItem' })
const props = defineProps<{
  modelValue: {
    name: string
    content: string
    file?: any
    path: string
    url?: string
  }
  showDelete?: boolean
  isLast?: boolean
}>()

const emit = defineEmits<{
  delete: []
  upload: [file: any]
  deleteImage: []
  'update:modelValue': [value: any]
}>()
// 图片预览
const previewVisible = ref(false)
const previewImage = ref('')

// 输入框聚焦状态
const isFocused = ref(false)

const handleUpload = (options: any) => {
  const file = options.file
  if (!file.type.startsWith('image/')) {
    ElMessage.error($t('questionBank.onlyImageFiles'))
    return
  }

  // 限制文件大小为2MB
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error($t('common.fileSizeLimitTxt', ['2']))
    return
  }

  // 创建本地预览URL
  const localUrl = URL.createObjectURL(file)
  const newValue = { ...props.modelValue, path: file.name, url: localUrl, file }
  emit('update:modelValue', newValue)
  emit('upload', { file, item: props.modelValue })
}

const handlePreview = () => {
  if (props.modelValue.url) {
    previewImage.value = props.modelValue.url
    previewVisible.value = true
  }
}

const handleDeleteImage = () => {
  // 如果是本地URL，需要释放内存
  if (props.modelValue.url && props.modelValue.url.startsWith('blob:')) {
    URL.revokeObjectURL(props.modelValue.url)
  }
  const newValue = { ...props.modelValue, path: '', url: '', file: null }
  emit('update:modelValue', newValue)
  emit('deleteImage')
}

const handleDelete = () => {
  emit('delete')
}

const updateContent = (value: string) => {
  const newValue = { ...props.modelValue, content: value }
  emit('update:modelValue', newValue)
}

// 输入框聚焦和失焦处理
const handleFocus = () => {
  isFocused.value = true
}

const handleBlur = () => {
  isFocused.value = false
}

// 验证选项内容
const validate = () => {
  if (!props.modelValue.content.trim()) {
    ElMessage.error($t('common.requiredTxt', ['选项' + props.modelValue.name + '内容']))
    return false
  }
  return true
}

defineExpose({
  validate
})
</script>

<template>
  <div class="w-full">
    <div class="flex items-stretch h-15.5">
      <div class="flex w-[90%] border border-transparent rounded transition-colors duration-200" :class="{ 'focused-border': isFocused }">
        <!-- 左侧选项名称 -->
        <div class="flex items-center justify-center w-8 h-full text-[#595959] font-normal"
          style="background: #DCDFE6; border-radius: 4px 0 0 4px;">
          {{ modelValue.name }}
        </div>

        <!-- 中间输入框 -->
        <div class="flex-1">
          <div class="h-full bg-white border-t border-b border-gray-200 flex items-center px-3">
            <el-input :model-value="modelValue.content" @update:model-value="(value: string) => updateContent(value)"
              @focus="handleFocus" @blur="handleBlur"
              :placeholder="$t('common.inputPhTxt', [$t('questionBank.referenceAnswer')])" clearable class="w-full" :style="{ height: '100%' }" />
          </div>
        </div>

        <!-- 右侧上传图片区域 -->
        <div class="bg-white border border-gray-200 flex items-center justify-center relative group"
          style="width: 80px; height: 64px; border-radius: 0 4px 4px 0;">
          <!-- 已上传图片显示 -->
          <div v-if="modelValue.url" class="w-full h-full relative cursor-pointer group" :style="{
            backgroundImage: `url(${modelValue.url})`,
            backgroundSize: 'contain',
            backgroundPosition: 'center',
            backgroundRepeat: 'no-repeat',
            borderRadius: '0 4px 4px 0'
          }" @click="handlePreview">
            <ImagePreviewActions :image-url="modelValue.url" :border-radius="'0 0 4px 0'" @preview="handlePreview"
              @delete="handleDeleteImage" />
          </div>

          <!-- 上传区域 -->
          <div v-else class="w-full h-full">
            <el-upload action="#" accept="image/*" :http-request="handleUpload" :auto-upload="true"
              :show-file-list="false" class="w-full h-full">
              <div
                class="w-full h-full flex flex-col items-center justify-center cursor-pointer hover:bg-gray-50 transition-colors duration-200"
                style="border-radius: 0 4px 4px 0;">
                <!-- 加号图标 -->
                <svg class="w-5 h-5 text-gray-400 mb-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6">
                  </path>
                </svg>
                <!-- 上传图片文字 -->
                <span class="text-xs text-gray-400">{{ $t('questionBank.uploadImage') }}</span>
              </div>
            </el-upload>
          </div>
        </div>
      </div>
      <!-- 删除选项按钮 -->
      <div v-if="showDelete || isLast" class="flex-1 flex items-center justify-center ml-1">
        <el-button size="small" circle link plain @click="handleDelete">
          <Trash2 class="w-4 h-4" />
        </el-button>
      </div>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" :title="$t('questionBank.imagePreview')" width="500px" append-to-body>
      <div class="flex justify-center">
        <img :src="previewImage" :alt="$t('questionBank.preview')" class="max-w-full h-auto rounded-lg shadow-lg" />
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 聚焦状态边框样式 */
.focused-border {
  border-color: #409eff !important;
}

/* 为子元素添加过渡效果 */
.flex-1 > div, 
.flex > div:nth-child(3) {
  transition: border-color 0.2s ease-in-out;
}

/* 聚焦时让子元素边框变为透明以避免重叠 */
.focused-border .flex-1 > div {
  border-top-color: transparent !important;
  border-bottom-color: transparent !important;
}

/* 聚焦时让右侧上传区域边框变为透明 */
.focused-border > div:nth-child(3) {
  border-color: transparent !important;
}

/* 移除 Element Plus 输入框的默认样式 */
:deep(.el-input__wrapper) {
  box-shadow: none !important;
  border: none !important;
  background: transparent !important;
  padding: 0 !important;
}

:deep(.el-input__inner) {
  border: none !important;
  box-shadow: none !important;
  background: transparent !important;
  padding: 0 !important;
  height: 100% !important;
}

/* 上传组件样式重置 */
:deep(.el-upload) {
  width: 100% !important;
  height: 100% !important;
}

:deep(.el-upload .el-upload-dragger) {
  width: 100% !important;
  height: 100% !important;
  border: none !important;
  background: transparent !important;
  border-radius: 4px !important;
}

/* 移动端响应式调整 */
@media (max-width: 768px) {
  .flex {
    flex-direction: column !important;
    height: auto !important;
  }

  .w-12 {
    width: 100% !important;
    height: 48px !important;
  }

  .w-16 {
    width: 100% !important;
    height: 64px !important;
  }

  .flex-1 {
    width: 100%;
  }
}
</style>
